//google.load('visualization', '1', {'packages':['corechart']});

/**
 * 
 */
$(document).ready(
	function()
	{
		$.fn.dataTableExt.oStdClasses.sWrapper = 'no-margin last-child';
		$.fn.dataTableExt.oStdClasses.sInfo = 'message no-margin';
		$.fn.dataTableExt.oStdClasses.sLength = 'float-left';
		$.fn.dataTableExt.oStdClasses.sFilter = 'float-right';
		$.fn.dataTableExt.oStdClasses.sPaging = 'sub-hover paging_';
		$.fn.dataTableExt.oStdClasses.sPagePrevEnabled = 'control-prev';
		$.fn.dataTableExt.oStdClasses.sPagePrevDisabled = 'control-prev disabled';
		$.fn.dataTableExt.oStdClasses.sPageNextEnabled = 'control-next';
		$.fn.dataTableExt.oStdClasses.sPageNextDisabled = 'control-next disabled';
		$.fn.dataTableExt.oStdClasses.sPageFirst = 'control-first';
		$.fn.dataTableExt.oStdClasses.sPagePrevious = 'control-prev';
		$.fn.dataTableExt.oStdClasses.sPageNext = 'control-next';
		$.fn.dataTableExt.oStdClasses.sPageLast = 'control-last';
		
		$.fn.updateTabs.enabledHash = false;
		
		$("#table-action").change(
			function()
			{
				if ( $(this).val() )
					$(this).parent().find('button[type=submit]').enableBt();
				else
					$(this).parent().find('button[type=submit]').disableBt();
			}
		);
		    
		if ( $('.datamask')[0] )
		    $('.datamask').inputmask({ 'mask': 'd/m/y', 'autounmask' : true});
		
		layoutUpload();
		
	}
);

function layoutUpload()
{
	$('.arquivo').each(
		function ( index, node )
		{
			var span = $('<span>');
			$(span).addClass('input-type-text');
			$(span).addClass('container-upload');
			$(span).attr('style', 'float:left;')
			//$(span).attr('id', 'container-upload');
			
			var input = $('<input>');
			$(input).attr('type', 'text');
			$(input).css({width: '90%'});
			
			var img = $('<img>');
			$(img).attr('width', 16);
			$(img).attr('height', 16);
			$(img).attr('src', baseUrl + '/public/images/admin/icons/fugue/magnifier.png' );
			$(img).css({float:'right'});
			
			$(span).append( input );
			$(span).append( img );
			
			$(node).change(
				function() 
				{
					var value = $(node).val();
					
					if ( value.length > 30 )
				    	value = value.substr( 0, 30 ) + '...';
					
					$(input).val( value );
				}
			);
			
			$(node).parent().append( span );
		}
	);
}

/**
 * 
 * @param check
 */
function checked ( check )
{
    $("input[type='checkbox']").attr('checked', check);
}

/**
 * 
 * @param form
 * @returns {Boolean}
 */
function status ( form )
{
    var data 	= [];
    var action 	= $('#table-action').val();
    var loading = $(form).find('th').eq(0);

    $(form).find("input[type='checkbox']:checked").each(
		function ()
		{
			data.push( $(this).val() );
		}
	);
	
    if ( !data.length ) 
    	return false;    
    
    $.ajax({
    	url: $(form).attr('action'),
    	dataType: 'json',
    	type: 'POST',
    	data: {
    		value: data, 
    		action: action
    	},
    	beforeSend: function ()
    	{
    		setStatusGrid( loading, {status: 'loading'} );	
    	},
    	success: function ( response )
    	{
    		if ( response ) {
    			
    			$(form).find("input[type='checkbox']:checked").each(
    				function ()
    				{
    					var small = $('<small>');
    					var text = parseInt(action) ? 'Liberado' : 'Bloqueado';
    					
    					small.text( text );
    					
    					$(this).parent().parent().find('td').eq(1).empty().append( small );
    				}
    			);
    			
    			setStatusGrid( loading, {status: 'success'} );
    			
    			checked( false );
    			
    		    $('#table-action').val('');
    		    $('#table-action').parent().find('button').disableBt();
    			
    		} else setStatusGrid( loading, {status: 'error'} );
    	},
    	error: function ( response )
    	{
    		setStatusGrid( loading, {status: 'error'} );
    	}
    });
    
    return false;
}

/**
 * 
 * @param th
 * @param status
 */
function setStatusGrid ( th, option )
{
    $(th).find('span').removeClass();
	
    if ( option ) {

    	switch ( option.status ) {
	    	case 'success':
	    		$(th).find('span').addClass('success');
	    		break;
					
		    case 'error':
		    	$(th).find('span').addClass('error');
		    	break;
					
		    case 'loading':
		    	$(th).find('span').addClass('loading');
		    	break;
    	}
    	
    }
}

/**
 * 
 * @param param
 */
function showDialog ( param )
{
    var option 	= {};

    option.maxWidth 		= 600;
    option.maxHeight 		= 600;
    option.scrolling 		= true;
    option.loadingMessage 	= 'Carregando...';

    for ( i in param )
    	option[i] = param[i];

    $.modal( option );	
}

function remove ( elem, url, codigo )
{
	if ( confirm('Desesa realmente remover?') ) {
		
		$.post(
			url,
			{
				id: codigo
			},
			function ( response )
			{
				if ( response ) {
					$(elem).parent().parent().remove();
					$('form').removeBlockMessages().blockMessage('O item foi removido com sucesso', {type: 'success'});
				} else {
					$('form').removeBlockMessages().blockMessage('O item não pode ser removido pois tem relacionamento com outros dados', {type: 'warning'});
				}
				
				setTimeout(function () { $('form').removeBlockMessages(); }, 5000);
			},
			'json'
		);
		
	}
}

/**
 * 
 * @param form
 * @return
 */
function submitAjax ( form, obj )
{
    var pars = $(form).serialize();
	
    hideErrorsForm();
	
    $.ajax({
    	type: 'POST',
    	data: pars,
    	dataType: 'json',
    	url: form.action,
    	beforeSend: function()
    	{
    		$('.block-footer button').attr('disabled', true);
    		
    		$(form).removeBlockMessages().blockMessage('Aguarde...', {type: 'loading'});
    	},
    	success: function ( response )
    	{
    		$('.block-footer button').attr('disabled', false );
	    
    		if ( obj && obj.callback )
    			execFunction( obj.callback, response );

    		$(form).removeBlockMessages();

    		$(response.description).each(
    			function ( index, value )
    			{
    				$(form).blockMessage( value.message, {type: value.level} );
    			}
    		);

    		if ( !response.status ) {

    			$(form).find('ul.errors').remove();

    			if ( response.errors )
    				showErrorsForm( response.errors );
    		}

    		$.modal.current.centerModal();
    	},
    	error: function ( response )
    	{
    		$('.block-footer button').attr('disabled', false);
    		
    		$(form).removeBlockMessages().blockMessage(response.message, {type: 'error'});
    	}
    });

    return false;
}

/**
 * 
 * @param fnName
 * @param params
 */
function execFunction( fnName, params )
{
    // Se existir o callback
    if ( typeof fnName == 'function' ) {
    	
    	return fnName( params );
    	
    } else if ( typeof fnName == 'string' ) {

    	var fn = window[fnName];

    	if ( typeof fn == 'function' )
    		return fn( params );
    	else
    		return false;
    
    }

    return false;
}

/**
 * 
 */
function errorUpload ( id )
{
	var error = false;
	
	$('.error').each(
		function ()
		{
			if ( id == this.id )
				error = true;
		}
	);
	
	if ( error )
		$('.container-upload').addClass('error');
}

/**
 * 
 * @param errors
 */
function showErrorsForm( errors )
{
	hideErrorsForm();
	
	for ( index in errors ) {
		
		$('#' + index).removeClass('error');
		
		var ul = $('<ul />');
		
		ul.addClass('errors');
		ul.attr('id', 'error_' + index );

		$('#' + index).addClass('error');
		$('#' + index).parent().append( ul );

		for ( m in errors[index] ) {
			var li = $('<li />').html( errors[index][m] );
			ul.append( li );
		}
		
	}
}

/**
 * 
 */
function hideErrorsForm ()
{
    $('*').removeClass('error');
    
    $('.errors').remove();    
    $('.check-error').remove();
}

/**
 * 
 * @param file
 */
function showFileSelected ( file )
{
	var value;
	
    if ( file.value.length > 30 )
    	value = file.value.substr( 0, 30 ) + '...';
    else
    	value = file.value;
    
    $(file).parent().find('span > .desc-file').val( value );
}

/**
 * 
 * @returns {String}
 */
function getUniqueId()
{
    var date = new Date();
    
    return date.getFullYear() + date.getMonth() + date.getDate() + date.getTime();
};

/**
 * 
 * @param id
 */
function showImage ( id )
{
    var div = $('<div>');
    var img = $('<img>');
	
    $(img).attr('src', baseUrl + '/imagem/' + id + '/450/300');
    $(div).append(img);
    
    var option = {};
    
	option.title 		= 'Imagem';
	option.content 		= $(div).html();
	option.resizeOnLoad = true;
	
	option.complete	= function() 
	{ 
		$.modal.current.centerModal();
	};
	
	showDialog( option );
	
	img.load(
		function()
		{
			$.modal.current.centerModal();
		}
	);
}

/**
 * 
 */
function resizeTab ()
{
	var css = {
		marginBottom: '20px',
		height: 'auto'
	};
	
	$('div.tabs').each(
		function ()
		{
			$(this).css(css);	
		}
	);
	
	$('#abas a').click(
		function()
		{
			$.modal.current.centerModal();
		}
	);	
	    
	$.modal.current.centerModal();    
}

/**
 * 
 */
function applyTemplateSetupTabs ()
{
	$.modal.current.find('.tabs.same-height, .side-tabs.same-height, .mini-tabs.same-height, .controls-tabs.same-height').equalizeTabContentHeight();

	$.modal.current.find('.js-tabs').updateTabs();

	$.modal.current.find('.js-tabs a[href^="#"]').click(function(event)
	{
		event.preventDefault();
		
		// If hashtag enabled
		if ($.fn.updateTabs.enabledHash)
		{
			// Retrieve hash parts
			var element = $(this);
			var hash = $.trim(window.location.hash || '');
			if (hash.length > 1)
			{
				// Remove hash from other tabs of the group
				var hashParts = hash.substring(1).split('&');
				var dummyIndex;
				while ((dummyIndex = $.inArray('', hashParts)) > -1)
				{
					hashParts.splice(dummyIndex, 1);
				}
				while ((dummyIndex = $.inArray('none', hashParts)) > -1)
				{
					hashParts.splice(dummyIndex, 1);
				}
				element.parent().parent().find('a[href^="#"]').each(function(i)
				{
					var index = $.inArray($(this).attr('href').substring(1), hashParts);
					if (index > -1)
					{
						hashParts.splice(index, 1);
					}
				});
			}
			else
			{
				var hashParts = [];
			}
			
			// Add current tab to hash (not if default)
			var defaultTab = getDefaultTabIndex(element.parent().parent());
			if (element.parent().index() != defaultTab)
			{
				hashParts.push(element.attr('href').substring(1));
			}
			
			// If only one tab, add a empty id to prevent document from jumping to selected content
			if (hashParts.length == 1)
			{
				hashParts.unshift('');
			}
			
			// Put hash, will trigger refresh
			window.location.hash = (hashParts.length > 0) ? '#'+hashParts.join('&') : '#none';
		}
		else
		{
			var li = $(this).closest('li');
			li.addClass('current').siblings().removeClass('current');
			li.parent().updateTabs();
		}
	});	
}